package com.gongpingjialoan.activity.main;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.AgentReCommendCarActivity;
import com.gongpingjialoan.activity.car.CarBuyDetailActivity;
import com.gongpingjialoan.activity.car.CarListActivity;
import com.gongpingjialoan.activity.car.DiscountDetailActivity;
import com.gongpingjialoan.activity.car.MyLikeCarActivity;
import com.gongpingjialoan.activity.car.NewUseCarAssResultActivity;
import com.gongpingjialoan.activity.car.SellCarDetailActivity;
import com.gongpingjialoan.activity.car.SellCarHistoryActivity;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.loans.LoanIndexActivity;
import com.gongpingjialoan.activity.particular.FirstActivity;
import com.gongpingjialoan.activity.sell.SellPrivateCarDetailActivity;
import com.gongpingjialoan.activity.tool.LicenceResultActivity;
import com.gongpingjialoan.activity.vip.VIPDetailActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.DataManager;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.AppUtils;
import com.gongpingjialoan.utility.FileUtils;
import com.gongpingjialoan.utility.LoanUtil;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.TimeUtils;
import com.gongpingjialoan.utility.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.UUID;

/**
 * 欢迎界面   wang
 *
 * @author Administrator
 */
public class SplashActivity extends AppCompatActivity {

    private final Handler mHandler = new Handler();

    // private ImageView mSplashImg;
    private ImageView baiduimageView, huaweiImageView;

    private String type, typeValue;

    private TextView textView;

    private static final int sleepTime = 2500;

    private Bundle mBundle;


    private final int LOGIN = 1099;

    private final int LOGINFROM_PAGE = 1100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        MobclickAgent.updateOnlineConfig(this);
        //   String channel = Utils.getAppMetaData(this, "UMENG_CHANNEL");

//        if ("Mi".equals(channel)) {
        // setContentView(R.layout.mi_layout);
//        } else {
        setContentView(R.layout.activity_splash_screen);
//            baiduimageView = (ImageView) this.findViewById(R.id.baidu);
//            huaweiImageView = (ImageView) this.findViewById(R.id.huawei);

        textView = (TextView) this.findViewById(R.id.tv_version);
        textView.setText("Version " + AppUtils.getVersionName(this));
//            if ("360".equals(channel)) {
//                huaweiImageView.setVisibility(View.VISIBLE);
//            } else {
        //  textView.setTextColor(getResources().getColor(R.color.new_color));
//            }
//        }
//        if ("failure".equals(GPJApplication.getInstance().getNotStatus)) {
//            GPJApplication.getInstance().getNotification();
//        }
        if ("failure".equals(GPJApplication.getInstance().getAppdataStatus)) {
            GPJApplication.getInstance().getAppInfoData();
        }
        if ("failure".equals(GPJApplication.getInstance().checkLoginStatus)) {
            GPJApplication.getInstance().checkLogin();
        }
        if (!DataManager.getInstance().getLoadingDataSuccess() && !GPJApplication.getInstance().fileDataStatus) {
            GPJApplication.getInstance().initData(new FileUtils());
        }

//        String code = getDeviceCode();
//        GPJApplication.getInstance().setDeviceCode(code);
//
//        Uri uri = getIntent().getData();
//        if (uri != null) {
//            type = uri.getQueryParameter("type");
//            typeValue = uri.getQueryParameter("typevalue");
//            mBundle = new Bundle();
//            mBundle.putString("type", type);
//            if (!TextUtils.isEmpty(typeValue)) {
//                mBundle.putString("typevalue", typeValue);
//                //如果是从估值报告过来的
//                if (MyPushIntentService.RECKON.equals(type)) {
//                    String city = uri.getQueryParameter("city");
//                    String description = uri.getQueryParameter("description");
//                    mBundle.putString("city", city);
//                    mBundle.putString("description", description);
//                }
//            }
//
//
//        } else {
//            mBundle = getIntent().getExtras();
//            if (mBundle != null) {
//                type = mBundle.getString("type", "");
//            }
//        }


        new Thread(new Runnable() {
            public void run() {
                // auto login mode, make sure all group and conversation is loaed before enter the main screen
                long start = System.currentTimeMillis();
                long costTime = System.currentTimeMillis() - start;
                //wait
                if (sleepTime - costTime > 0) {
                    try {
                        Thread.sleep(sleepTime - costTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                toHome();
            }
        }).start();
    }

    public void checkLogin() {
        UserManager mUserManager = new UserManager(this);
        Utils.LogD("checkLogin begin ");
        mUserManager.CheckLogin(new UserManager.OnCheckLoginResponse() {
            @Override
            public void onCheckLoginSuccess() {
                toMainActivity();
                finish();
            }

            @Override
            public void onCheckLoginError(final String errorMessage) {
                toMainActivity();
                finish();
            }
        });

    }

    private void toHome() {
        //本地 boolean是否通过审核
        boolean isPassed = (boolean) SharedPreferencesUtil.get(this, "isPassed", false);
        System.out.println("===本地isPassed===>>>> "+isPassed);
        if (isPassed) {
            checkLogin();
        } else {
            // 先根据时间对比 如大于目标日期 则进入主页
            if (System.currentTimeMillis() > TimeUtils.getStringToDate("2018-01-01")) {
                SharedPreferencesUtil.put(this, "isPassed", true);
                checkLogin();
                System.out.println("===时间超出===>>>>");
                return;
            }
            if (isPassed()) {
                SharedPreferencesUtil.put(this, "isPassed", true);
                checkLogin();
            } else {
                toFirstActivity();
            }
        }
    }

    private void toMainActivity() {
        boolean ishow = (boolean) SharedPreferencesUtil.get(this, "ishow", false);
        Intent it;
        if (!ishow) {
            it = new Intent(SplashActivity.this, GuideActivity.class);
            startActivity(it);
            finish();
        } else {
            it = new Intent(SplashActivity.this, LoanIndexActivity.class);
            startActivity(it);
            finish();
        }
    }

    private void toFirstActivity() {
        Intent it;
        it = new Intent(SplashActivity.this, FirstActivity.class);
        startActivity(it);
        finish();
    }

    //通过后端返回字符串判断是否过审
    private boolean isPassed() {
        String passed = GPJApplication.getInstance().getPassed();
        System.out.println("====后端返回passed==>>>>"+passed);
        if (passed == null || "1.0.0".equals(passed)) {
            return false;
        }
        return true;
    }


    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    private String getVersionName() {
        String version = "";
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            version = packInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    private void goGuideOrMain() {
//        int last_version = (int) SharedPreferencesUtil.get(this, "version_code", -1);
//        int current_version = GPJApplication.getInstance().verison_code;

//        if (TextUtils.isEmpty(type)) {
////            if (!ishow) {
////                startActivity(new Intent(SplashActivity.this, GuideActivity.class));
////                finish();
////            } else {
//
////                UserManager mUserManager = new UserManager(SplashActivity.this);
////                mUserManager = mUserManager.LoadUserInfo();
//                Intent it;
////                if (TextUtils.isEmpty(mUserManager.getToken()) || "failure".equals(GPJApplication.getInstance().checkLoginStatus)) {
////                    it = new Intent(SplashActivity.this, LoginActivity.class);
////                    it.putExtra("show_back", false);
////                    startActivityForResult(it, LOGIN);
////                } else {
//                    it = new Intent(SplashActivity.this, LoanIndexActivity.class);
//                    startActivity(it);
//                    finish();
////                }
//
////            }
////            SplashActivity.this.finish();
//        } else {
//            UserManager mUserManager = new UserManager(SplashActivity.this);
//            mUserManager = mUserManager.LoadUserInfo();
//            Intent it;
//            if (TextUtils.isEmpty(mUserManager.getToken()) || "failure".equals(GPJApplication.getInstance().checkLoginStatus)) {
//                it = new Intent(SplashActivity.this, LoginActivity.class);
//                it.putExtra("show_back", false);
//                startActivityForResult(it, LOGINFROM_PAGE);
//            } else {
//                goAppFromPage();
//            }
//        }
    }


    //从网页进入app
    private void goAppFromPage() {
        Intent resultIntent = new Intent();
        resultIntent.putExtras(mBundle);
        if (MyPushIntentService.CAR_DETAIL.equals(type) || MyPushIntentService.PRICECHANGE.equals(type)) {
            resultIntent.setClass(this, CarBuyDetailActivity.class);
        } else if (MyPushIntentService.SELLCAR.equals(type) || MyPushIntentService.CHOOSECAR.equals(type) || MyPushIntentService.RECOMMEND.equals(type) || MyPushIntentService.BILLBOARD.equals(type) || MyPushIntentService.BILLBOARDTYPE.equals(type) || MyPushIntentService.PROMINTIONLIST.equals(type) || MyPushIntentService.MARKET.equals(type)) {
            resultIntent.setClass(this, LoanIndexActivity.class);
        } else if (MyPushIntentService.VIPLIST.equals(type) || MyPushIntentService.CUSTOMLIST.equals(type)) {
            resultIntent.setClass(this, CarListActivity.class);
        } else if (MyPushIntentService.SELLCARHISTORYDETAIL.equals(type)) {
            resultIntent.setClass(this, SellCarDetailActivity.class);
        } else if (MyPushIntentService.PROMOTIONDETAIL.equals(type)) {
            resultIntent.setClass(this, DiscountDetailActivity.class);
        } else if (MyPushIntentService.RECKON.equals(type)) {
            resultIntent.setClass(this, ValueReportActivity.class);
        } else if (MyPushIntentService.VIOLATION.equals(type)) {
            resultIntent.setClass(this, LicenceResultActivity.class);
        } else if (MyPushIntentService.SELLCARHISTORY.equals(type)) {
            resultIntent.setClass(this, SellCarHistoryActivity.class);
        } else if (MyPushIntentService.MYCAR.equals(type)) {
            resultIntent.setClass(this, MyLikeCarActivity.class);
        } else if (MyPushIntentService.SELLPRIVATECAR.equals(type)) {
            resultIntent.setClass(this, SellPrivateCarDetailActivity.class);
        } else if (MyPushIntentService.PERSONERSEllRECONDS.equals(type)) {
            resultIntent.setClass(this, SellCarHistoryActivity.class);
            resultIntent.putExtra("private", true);
        } else if (MyPushIntentService.RECOMENDCARLIST.equals(type)) {
            resultIntent.setClass(this, AgentReCommendCarActivity.class);
        } else if (MyPushIntentService.MESSAGECENTER.equals(type)) {
//            resultIntent.setClass(this, MessageCenterActivity.class);
        } else if (MyPushIntentService.VIPBUY.equals(type)) {
            resultIntent.setClass(this, VIPDetailActivity.class);
        } else if (MyPushIntentService.RECKONBUY.equals(type)) {
            resultIntent.setClass(this, NewUseCarAssResultActivity.class);
        }

        if (MyPushIntentService.LOANRESULT.equals(type)) {
            getLoanStatus();
        } else {
            startActivity(resultIntent);

        }
        SplashActivity.this.finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    //
    //获取设备号
    private String getDeviceCode() {
        String uniqueId = "";
        try {
            final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
            final String tmDevice, tmSerial, androidId;
            tmDevice = "" + tm.getDeviceId();
            tmSerial = "" + tm.getSimSerialNumber();
            androidId =
                    ""
                            + android.provider.Settings.Secure.getString(getContentResolver(),
                            android.provider.Settings.Secure.ANDROID_ID);
            UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
            uniqueId = deviceUuid.toString();

            Utils.LogD("uniqueId = " + uniqueId);
        } catch (Exception e) {
            Utils.LogE("获取机器码异常：" + e.getMessage());
        }
        return uniqueId;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.splash_screen, menu);
        return true;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == LOGIN) {
                Intent it = new Intent(SplashActivity.this, LoanIndexActivity.class);
                startActivity(it);
                finish();
            } else if (requestCode == LOGINFROM_PAGE) {
                goAppFromPage();
            }


        }
    }


    private void getLoanStatus() {
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(SplashActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(SplashActivity.this, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    LoanUtil.toLoanData(json);
                    LoanUtil.goToPerfect(SplashActivity.this);
//                    setViewInfo(LoanStatusData.getInstance().getStatus());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);
        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.campaigncars_evaluations);
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
    }
}
